package com.erbao.dp.itrator;

/**
 * @author CaoBaoYin
 * @since 2021/9/18 18:33
 */
public class LinkedList_<E> implements Collection_<E> {
    private int size;
    private Node<E> head;
    private Node<E> tail;

    public LinkedList_() {
    }

    @Override
    public boolean add(E e) {
        Node<E> node = new Node<>();
        node.value = e;
        if (size == 0) {
            head = node;
        } else {
            tail.next = node;
        }
        tail = node;

        size ++;

        return true;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator_<E> iterator() {
        return new LinkedListIterator<>(head);
    }

    private static class LinkedListIterator<E> implements Iterator_<E>{
        private Node<E> cursor;

        public LinkedListIterator(Node<E> cursor) {
            Node<E> node = new Node<>();
            node.value = cursor.value;
            node.next = cursor.next;
            this.cursor = node;
        }

        @Override
        public boolean hasNext() {
            return cursor != null;
        }

        @Override
        public E next() {
            E result = cursor.value;
            cursor = cursor.next;
            return result;
        }
    }

    private static class Node<E> {
        E value;
        Node<E> next;
    }
}
